//
//  NewsDetailViewController.m
//  NetEase
//
//  Created by Apple on 2018/5/5.
//  Copyright © 2018年 techbird. All rights reserved.
//

#import "NewsDetailViewController.h"
#import "NetworkManager.h"
#import <ESPictureBrowser.h>

@interface NewsDetailViewController ()<UIWebViewDelegate,ESPictureBrowserDelegate>
@property (weak, nonatomic)UIWebView *webview;
@property (strong, nonatomic) NewsModel *newsModel;
@property (strong, nonatomic) NSMutableArray *imgArr;

@end

@implementation NewsDetailViewController

- (instancetype)initWithNewsModel:(NewsModel *)newsModel{
    self = [super init];
    if (self) {
        _newsModel = newsModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _imgArr = [NSMutableArray array];
    [self setupUI];
    [self loadNewsDetailData];
}

- (void)setupUI{
    self.view.backgroundColor = UIColor.whiteColor;
    UIWebView *webView = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    webView.delegate = self;
    [self.view addSubview:webView];
    self.webview = webView;
}

- (NSString *)pictureView:(ESPictureBrowser *)pictureBrowser highQualityUrlStringForIndex:(NSInteger)index{
    return self.imgArr[index];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlString = request.URL.absoluteString;
    NSArray *components = [urlString componentsSeparatedByString:@"::"];
    NSLog(@"components %@",components);
    if([[components firstObject] isEqualToString: @"imagetagclick"]){
        NSInteger index = [components[1] integerValue];
        CGFloat X = [components[2] floatValue];
        CGFloat Y = [components[3] floatValue];
        CGFloat W = [components[4] floatValue];
        CGFloat H = [components[5] floatValue];
        UIView *fromView = [[UIView alloc]initWithFrame:CGRectMake(X, Y, W, H)];
        fromView.backgroundColor = UIColor.redColor;
        [self.webview addSubview:fromView];
        ESPictureBrowser *browser = [ESPictureBrowser new];
        browser.delegate = self;
        [browser showFromView:fromView picturesCount:self.imgArr.count currentPictureIndex:index];
        [fromView removeFromSuperview];
        return NO;
    }
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *jsString =
    @"function setImage(){\
    var imgs = document.getElementsByTagName('img');\
    for (var i=0;i<imgs.length;i++){\
    imgs[i].setAttribute(\"onClick\",\"imageClick(\"+i+\")\");\
    }\
    }\
    function imageClick(i){\
    var rect = getImageRect(i);\
    var url = \"imagetagclick::\"+i+\"::\"+rect;\
    document.location = url;\
    }\
    function getImageRect(i){\
    var imgs = document.getElementsByTagName(\"img\");\
    var rect;\
    rect = imgs[i].getBoundingClientRect().left+\"::\";\
    rect = rect+imgs[i].getBoundingClientRect().top+\"::\";\
    rect = rect+imgs[i].width+\"::\";\
    rect = rect+imgs[i].height;\
    return rect;\
    }";
    [webView stringByEvaluatingJavaScriptFromString:jsString];
    //需要用一下js中的方法才可以执行
    [webView stringByEvaluatingJavaScriptFromString:@"setImage();"];
}

- (void)loadNewsDetailData{
    NSString *urlString = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",self.newsModel.docid];
    [[NetworkManager sharedManager] GETWithURLString:urlString parameters:nil success:^(NSDictionary *responseObject){
        NSDictionary *result = responseObject[self.newsModel.docid];
        NSString *html = result[@"body"];
        NSArray *imgArr = result[@"img"];
        for (NSDictionary *img in imgArr) {
            NSString *imgTag = img[@"ref"];
            NSString *imgSrc = img[@"src"];
            NSString *imgHtmlTag = [NSString stringWithFormat:@"<img src=\"%@\"/>",imgSrc];
            html = [html stringByReplacingOccurrencesOfString:imgTag withString:imgHtmlTag];
            [self.imgArr addObject:imgSrc];
        }
        NSString *pathFile = [[NSBundle mainBundle] pathForResource:@"newsDetail.css" ofType:nil];
        NSString *css = [NSString stringWithContentsOfFile:pathFile encoding:NSUTF8StringEncoding error:NULL];
        html = [html stringByAppendingString:css];
        [self.webview loadHTMLString:html baseURL:nil];
        NSLog(@"%@",html);
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

@end
